package com.cosc716.simulator;

import java.util.ArrayList;

/**
 * @author davidmessing
 *
 */
public class RunLoop {
	
	// container for command objects
	private ArrayList<RunLoopCommand>queue;

	public RunLoop() {
		// initialize an empty queue
		this.queue = new ArrayList<RunLoopCommand>();
	}
	
	public boolean containsCommand(RunLoopCommand command) {
		
		// check for valid queue
		if ( null == this.queue) {
			return false;
		}
		
		// check if queue contains command
		if ( this.queue.contains(command) ) {
			return true;
		}
		
		return false;
	}
	
	public void addCommand(RunLoopCommand command) throws RunLoopException {
		
		// check for valid queue and initialize if not found
		if ( null == this.queue) {
			this.queue = new ArrayList<RunLoopCommand>();
		}
		
		/* The queue should not be able to hold more than one 
		 * reference to the same RunLoopCommand object. Therefore,
		 * we check if queue already contains command before adding. 
		 */
		if ( this.containsCommand(command) ) {
			throw new RunLoopException(command + " cannot be added more than once.");
		}
		else {
			// add the command to the queue
			this.queue.add(command);
		}
	}
	
	public void removeCommand(RunLoopCommand command) {
		
		// check for valid queue
		if ( null == this.queue) {
			return;
		}
		
		// check if command exists in queue
		if ( this.containsCommand(command) ) {
			this.queue.remove(command);
		}
		
	}

	public void run(int interval) {
		
		// check for valid queue and initialize if not found
		if (null == this.queue) {
			this.queue = new ArrayList<RunLoopCommand>();
		}
		
		/* To process the RunLoop, simply iterate over the queue
		 * and execute every RunLoopCommand in order. 
		 */
		for (RunLoopCommand c: this.queue) {
			c.execute(interval);
		}
	}
}
